package org.example.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.example.model.Result;
import org.example.model.User;
import org.example.service.UserLoginService;
import org.example.util.AliYunImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/userApi/loginCtl")
public class UserLoginController {
    @Autowired
    private UserLoginService userLoginService;

    @RequestMapping(path = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
        //加密密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User user1 = userLoginService.login(user.getAccount(), user.getPassword());
        if (user1 != null) {
            System.out.println("登录成功");
            return new Result(200, "登录成功", user1);
        } else {
            return new Result(401, "登录失败", null);
        }
    }


    @Autowired
    private AliYunImage aliYunImage;
    @RequestMapping(path = "/uploadImg",method = RequestMethod.POST)
    public Result uploadImg(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        System.out.println(file.getInputStream());//获取图片流
        System.out.println(file.getOriginalFilename());
        String newFileName = new Date().getTime()+file.getOriginalFilename();
        //连接oss
        OSS ossClient = new OSSClientBuilder().build("https://"+aliYunImage.getEndpoint(),
                aliYunImage.getAccessKeyId(), aliYunImage.getAccessKeySecret());
        //长传文件
        ossClient.putObject(aliYunImage.getBucketName(), newFileName,
                file.getInputStream());
        //拼接文件在oss中访问地址
        String url = "https://"+aliYunImage.getBucketName()+"."+aliYunImage.getEndpoint()+"/"+newFileName;

        System.out.println("上传成功！！");
        return new Result(200, "上传成功", url);
    }
    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public Result register(@RequestBody User user) {
        //检查account是否存在
        if (userLoginService.checkAccount(user.getAccount())!=null) {
            return new Result(401, "账号已存在", null);
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userLoginService.register(user);
        return new Result(200, "注册成功", null);
    }

}
